import java.sql.*;

// A simple class to help use a database
public class DB {
  private Connection connect = null;
  private String dbURL = "jdbc:mysql://157.62.23.204/p2t3";
  private String username = "p2t3";
  private String password = "p2t3";

  public DB() {
    getConnection();
  }

  private void getConnection() {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      connect = DriverManager.getConnection(dbURL, username, password);
    }
    catch (ClassNotFoundException e) {
      System.out.println("Database driver not found.");
    }
    catch (Exception e) {
      System.out.println("Other Exception");
    }
  }

  public ResultSet doQuery(String q) {
    ResultSet rs = null;
    PreparedStatement ps = null;
    try {
      ps = connect.prepareStatement(q);
      rs = ps.executeQuery();
    }
    catch (SQLException e) {
      System.out.println("SQLException: " + e.getMessage());
      System.out.println("SQLState: " + e.getSQLState());
      System.out.println("VendorError: " + e.getErrorCode());
    }
    catch (Exception e) {
      System.out.println("Other Exception");
    }
    return rs;
  }

  public void doUpdate(String q) {
    // version to Update, Delete, and Insert
    // no resultset is returned

    PreparedStatement ps = null;
    try {
      ps = connect.prepareStatement(q);
      ps.executeUpdate();
    }
    catch (SQLException e) {
      System.out.println("SQLException: " + e.getMessage());
      System.out.println("SQLState: " + e.getSQLState());
      System.out.println("VendorError: " + e.getErrorCode());
    }
    catch (Exception e) {
      System.out.println("Other Exception");
    }
  }

  public static void main(String[] args) throws Exception {
    DB mydb = new DB();
    String preparedSQL = "select petName, species from pet";
    ResultSet rs = mydb.doQuery(preparedSQL);
    while(rs.next()) {
      System.out.println(rs.getString(1) + " \t " + rs.getString(2));
    }
  }
}

